﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using QDT.Common;
using QDT.Core;
using QDT.Core.Domain;
using QDT.Core.Members;
using QDT.Core.Projects;

namespace QDT.Web.Admin.Controllers
{
    public class ExportController : BaseController
    {

        public ActionResult ChangeList(DateTime? time, string info, int? page)
        {
            const int pageSize = 200;
            var pageNumber = page ?? 1;

            var filter = PredicateExtensionses.True<UserTransLog>();

            if (time == null) return Error("请选择时间");

            var startTime = ((DateTime)time).Date;
            var endTime = startTime.AddDays(1);
            filter = filter.And(x => x.Time >= startTime && x.Time < endTime);

            if (!string.IsNullOrWhiteSpace(info)) filter = filter.And(x => x.Info.Contains(info));

            var source = DbProvider.D<UserTransLog>()
                .Where(filter)
                .OrderByDescending(x => x.ID)
                .ToPagedList(pageNumber - 1, pageSize);
            var fileString = new StringBuilder().Append("编号,交易类型,操作备注,操作时间,会员名称,用户组,冻结金,资金变动,可用余额,\n");
            source.Each(x =>
                {
                    var user = DbProvider.GetByID<User>(x.UserID);
                    var userGroup = DbProvider.GetByID<UserGroup>(user.GroupID);
                    fileString.Append(x.ID + "," + x.Trade.ToLocalizable() + "," + x.Info.Replace(',', '，') + "," + x.Time + "," +
                                      user.UserName + "," + userGroup.Name + "," + x.LockMoney.ToString("0.00") + "," +
                                      x.Money.ToString("0.00") + "," + x.OverMoney.ToString("0.00") + "\n");
                });
            var fileContents = Encoding.UTF8.GetBytes(fileString.ToString());
            return File(fileContents, "application/csv", GetRandomFileName());
        }

        public ActionResult RepayingList(DateTime? time)
        {
            var filter = PredicateExtensionses.True<Project>();

            if (time == null) return Error("请选择时间");

            var startTime = ((DateTime)time).Date;
            var endTime = startTime.AddDays(1);
            filter = filter.And(x => x.NextRepayTime >= startTime && x.NextRepayTime < endTime);

            var source = DbProvider.D<Project>().Where(filter).ToList();
            var fileString = new StringBuilder().Append("编号,下一次还款时间,开始还款时间,贷款名称,贷款类型,期限,借款人,投标状态,\n");
            source.Each(x =>
            {
                var user = DbProvider.GetByID<User>(x.UserID);
                var type = DbProvider.GetByID<ProjectType>(x.TypeID);
                fileString.Append(x.ID + "," + x.NextRepayTime.Value + "," + x.RepayStartTime.Value + "," + x.Name.Replace(',', '，') + "," +
                                  type.Name + "," + x.RepayTime + "个月," + user.UserName + "," +
                                  x.Status.ToLocalizable() + ",\n");
            });
            var fileContents = Encoding.UTF8.GetBytes(fileString.ToString());
            return File(fileContents, "application/csv", GetRandomFileName());
        }

        public ActionResult CarryList()
        {
            var filter = PredicateExtensionses.True<UserCarry>();

            filter = filter.And(x => x.Status == 0);

            var source = DbProvider.D<UserCarry>().Where(filter).ToList();
            var fileString = new StringBuilder().Append("编号,申请日期,会员名称,姓名,提现金额,开户行,开户行所在地,开户行网点,银行卡卡号,\n");
            source.Each(x =>
            {
                var user = DbProvider.GetByID<User>(x.UserId);
                var bank = DbProvider.GetByID<Bank>(x.BankId);
                var region = DbProvider.GetByID<RegionConfig>(x.RegionLv2).Name + " " +
                             DbProvider.GetByID<RegionConfig>(x.RegionLv3).Name;
                fileString.Append(x.ID + "," + x.CreateTime + "," + user.UserName + "," + user.RealName + "," + x.Money.ToString("0.00") + "," + 
                                  bank.Name + "," + region + "," + x.BankZone + "," + "'" + x.BankCard.Replace(" ", "") + ",\n");
            });
            var fileContents = Encoding.UTF8.GetBytes(fileString.ToString());
            return File(fileContents, "application/csv", GetRandomFileName());
        }

        /// <summary>
        /// 得到随机的文件名
        /// </summary>
        private string GetRandomFileName()
        {
            var random = new Random((int)(DateTime.Now.Ticks));
            var next = random.Next(Int32.MaxValue).ToString(CultureInfo.InvariantCulture);
            return DateTime.Now.ToShortDateString() + "_" + next + ".csv";
        }


    }
}
